#pragma once

#include <iostream>
#include <memory>
#include <cstdlib>
#include <string>
#include <strings.h>
#include <functional>
#include "InetAddr.hpp"
#include "Logger.hpp"
#include "Mutex.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

// 回调函数
using callback_t = std::function<void(int sockfd, std::string massage, InetAddr addr)>;

const static int defaultsockfd = -1;

class ChatSever
{
public:
    ChatSever(uint16_t port, callback_t cb)
        : _sockfd(defaultsockfd),
          _port(port),
          _is_running(false),
          _cb(cb)
    {
    }
    // 初始化
    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success!" << _sockfd;
        // 2.bind链接
        // 2.1填充IP和port
        InetAddr local(_port);
        // 2.2和socketfd链接
        int n = bind(_sockfd, local.Addr(), local.Length());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success!";
    }
    // 启动
    void Start()
    {
        _is_running = true;
        while (_is_running)
        {
            char buffer[1024];
            buffer[0] = 0; // 清空数据
            struct sockaddr_in pere;
            socklen_t len = sizeof(pere);
            // 读取数据
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&pere, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                // 获取对方ip和port
                InetAddr clintaddr(pere);
                LOG(LogLevel::DEBUG) << "get a clint info# " << "[ " <<clintaddr.Ip() << " : "
                                     << clintaddr.Port() << " ] " << buffer;
                // 回调
                std::string massage = buffer;
                _cb(_sockfd, massage, clintaddr);
            }
        }
        _is_running = false;
    }
    // 关闭
    void Stop()
    {
        _is_running = false;
    }
    ~ChatSever()
    {
    }
private:
    int _sockfd;
    uint16_t _port;
    bool _is_running;
    callback_t _cb;
};